﻿using adminTemplateApi.Common;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace adminTemplateApi.Controllers
{
    public class CommonResultFilter: ActionFilterAttribute, IExceptionFilter
    {
        public override void OnResultExecuting(ResultExecutingContext context)
        {
            if (context.Result is ObjectResult)
            {
                var objectResult = (ObjectResult)context.Result;
                if (objectResult.Value == null)
                {
                    context.Result = new ObjectResult(new { code = 404, msg = "未找到资源" });
                }
                else
                {
                    context.Result = new ObjectResult(new { code = 200, msg = "", result = objectResult.Value });
                }
            }
            else if (context.Result is EmptyResult)
            {
                context.Result = new ObjectResult(new { code = 404, msg = "未找到资源" });
            }
            else if (context.Result is ContentResult)
            {
                context.Result = new ObjectResult(new { code = 200, msg = "", result = ((ContentResult)context.Result).Content });
            }
            else if (context.Result is StatusCodeResult)
            {
                context.Result = new ObjectResult(new { code = ((StatusCodeResult)context.Result).StatusCode, sub_msg = "", msg = "" });
            }
        }

        public void OnException(ExceptionContext context)
        {
            if (context.Exception is MyError) {
                MyError myError = (MyError)context.Exception;
                context.Result = new ObjectResult(new { code = myError.Code, msg = myError.Message });
            }
            else
            {
                context.Result = new ObjectResult(new { code = 500, msg = context.Exception.Message });
            }
        }
    }
}
